import { Request, Response } from 'express';
import { policyNewsService } from './service';
import { AuthRequest } from '../../types/auth';
import { ApiResponse } from '../../types/page';
import { PolicyNews, PolicyNewsType } from '../../entities/PolicyNews';

type PolicyNewsListResponse = {
  records: PolicyNews[];
  total: number;
  size: number;
  current: number;
  pages: number;
};

/**
 * 获取政策新闻列表
 */
export const getPolicyNewsList = async (req: AuthRequest, res: Response) => {
  try {
    const current = Number(req.query.page) || 1;
    const size = Number(req.query.size) || 10;
    const type = req.query.type !== undefined ? Number(req.query.type) : undefined;
    const isActive = req.query.isActive !== undefined ? req.query.isActive === 'true' : undefined;
    const title = req.query.title as string;
    const startDate = req.query.startDate as string;
    const endDate = req.query.endDate as string;
    
    const { news, total } = await policyNewsService.getPolicyNewsList({
      page: current,
      pageSize: size,
      type,
      isActive,
      title,
      startDate,
      endDate
    });
    
    const response: ApiResponse<PolicyNewsListResponse> = {
      success: true,
      data: {
        records: news,
        total,
        size,
        current,
        pages: Math.ceil(total / size)
      }
    };
    
    res.json(response);
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取政策新闻列表失败',
      error: error.message
    });
  }
};

/**
 * 获取政策新闻详情
 */
export const getPolicyNewsDetail = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const news = await policyNewsService.getPolicyNewsById(id);
    
    if (!news) {
      return res.status(404).json({
        success: false,
        message: '政策新闻不存在'
      });
    }
    
    res.json({
      success: true,
      data: news
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取政策新闻详情失败',
      error: error.message
    });
  }
};

/**
 * 创建政策新闻
 */
export const createPolicyNews = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const newsData = req.body;
    
    // 验证必填字段
    if (!newsData.type || !newsData.title || !newsData.publisher) {
      return res.status(400).json({
        success: false,
        message: '类型、标题和发布人为必填项'
      });
    }
    
    // 验证内容和链接必须至少提供一个
    if (!newsData.content && !newsData.linkUrl) {
      return res.status(400).json({
        success: false,
        message: '内容和链接地址必须至少提供一个'
      });
    }
    
    // 验证类型是否有效
    if (!Object.values(PolicyNewsType).includes(newsData.type)) {
      return res.status(400).json({
        success: false,
        message: '无效的新闻类型'
      });
    }
    
    const news = await policyNewsService.createPolicyNews(newsData, userId);
    
    res.json({
      success: true,
      message: '创建政策新闻成功',
      data: news
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '创建政策新闻失败',
      error: error.message
    });
  }
};

/**
 * 更新政策新闻
 */
export const updatePolicyNews = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const id = req.params.id;
    const newsData = req.body;
    
    // 验证类型是否有效
    if (newsData.type && !Object.values(PolicyNewsType).includes(newsData.type)) {
      return res.status(400).json({
        success: false,
        message: '无效的新闻类型'
      });
    }
    
    // 如果同时提供了内容和链接，需要检查
    if (newsData.content === '' && newsData.linkUrl === '') {
      return res.status(400).json({
        success: false,
        message: '内容和链接地址必须至少提供一个'
      });
    }
    
    const news = await policyNewsService.updatePolicyNews(id, newsData, userId);
    
    if (!news) {
      return res.status(404).json({
        success: false,
        message: '政策新闻不存在'
      });
    }
    
    res.json({
      success: true,
      message: '更新政策新闻成功',
      data: news
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '更新政策新闻失败',
      error: error.message
    });
  }
};

/**
 * 删除政策新闻
 */
export const deletePolicyNews = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const result = await policyNewsService.deletePolicyNews(id);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '政策新闻不存在或删除失败'
      });
    }
    
    res.json({
      success: true,
      message: '删除政策新闻成功'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '删除政策新闻失败',
      error: error.message
    });
  }
};

/**
 * 更新政策新闻状态
 */
export const updatePolicyNewsStatus = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const id = req.params.id;
    const { isActive } = req.body;
    
    if (typeof isActive !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: '状态参数无效'
      });
    }
    
    const result = await policyNewsService.updatePolicyNewsStatus(id, isActive, userId);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '政策新闻不存在或更新失败'
      });
    }
    
    res.json({
      success: true,
      message: `${isActive ? '启用' : '禁用'}政策新闻成功`
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '更新政策新闻状态失败',
      error: error.message
    });
  }
};

/**
 * 获取招生动态列表（前台接口）
 */
export const getAdmissionNews = async (req: Request, res: Response) => {
  try {
    const limit = Number(req.query.limit) || 10;
    const news = await policyNewsService.getNewsByType(PolicyNewsType.ADMISSION_DYNAMIC, limit);
    
    res.json({
      success: true,
      data: news
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取招生动态失败',
      error: error.message
    });
  }
};

/**
 * 获取专业介绍列表（前台接口）
 */
export const getMajorIntroductions = async (req: Request, res: Response) => {
  try {
    const limit = Number(req.query.limit) || 10;
    const news = await policyNewsService.getNewsByType(PolicyNewsType.MAJOR_INTRODUCTION, limit);
    
    res.json({
      success: true,
      data: news
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取专业介绍失败',
      error: error.message
    });
  }
}; 